{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "ur8xi4C7S06n"
   },
   "outputs": [],
   "source": [
    "# Copyright 2019 Google LLC\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     https://www.apache.org/licenses/LICENSE-2.0 \n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "HosWdaE-KieL"
   },
   "source": [
    "# **Retail Product Stockouts Prediction using AutoML Tables**\n",
    "\n",
    "<table align=\"left\">\n",
    "  <td>\n",
    "    <a href=\"https://colab.sandbox.google.com/github/GoogleCloudPlatform/python-docs-samples/blob/master/tables/automl/notebooks/retail_product_stockout_prediction/retail_product_stockout_prediction.ipynb\">\n",
    "      <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
    "    </a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/tables/automl/notebooks/retail_product_stockout_prediction/retail_product_stockout_prediction.ipynb\">\n",
    "      <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
    "      View on GitHub\n",
    "    </a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "tvgnzT1CKxrO"
   },
   "source": [
    "## **Overview**\n",
    "\n",
    "AutoML Tables enables you to build machine learning models based on tables of your own data and host them on Google Cloud for scalability. This Notebook demonstrates how you can use AutoML Tables to solve a product stockouts problem in the retail industry. This problem is solved using a binary classification approach, which predicts whether a particular product at a certain store will be out-of-stock or not in the next four weeks. Once the solution is built, you can plug this in with your production system and proactively predict stock-outs for your business.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "EvDhOgYL8V_K"
   },
   "source": [
    "### **Dataset**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8pfea4To7XBv"
   },
   "source": [
    "In this solution, you will use two datasets: Training/Evaluation data and Batch Prediction inputs. To access the datasets in BigQuery, you need the following information.\n",
    "\n",
    "##### **Training/Evaluation dataset**\n",
    "\n",
    "  *  `Project ID: product-stockout`\n",
    "  *  `Dataset ID: product_stockout`\n",
    "  *  `Table ID: stockout`\n",
    "  \n",
    "##### **Batch Prediction inputs**\n",
    "\n",
    "  *  `Project ID: product-stockout`\n",
    "  *  `Dataset ID: product_stockout`\n",
    "  *  `Table ID: batch_prediction_inputs`\n",
    "\n",
    "##### **Data Schema**\n",
    "\n",
    "<table align=\"left\">\n",
    "  <thead>\n",
    "    <tr>\n",
    "      <th> Field name </th>\n",
    "      <th> Datatype </th>\n",
    "      <th> Type </th>\n",
    "      <th> Description </th>\n",
    "    </tr>\n",
    "  </thead>\n",
    "  <tbody>\n",
    "    <tr>\n",
    "      <td>Item_Number</td>\n",
    "      <td>STRING</td>\n",
    "      <td>Identifier</td>\n",
    "      <td>This is the product/ item identifier</td>\n",
    "    </tr>\n",
    "    <tr>\n",
    "\t<td>Category</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Identifier</td>\n",
    "\t<td>Several items could belong to one category</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Vendor_Number</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Identifier</td>\n",
    "\t<td>Product vendor identifier</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Store_Number</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Identifier</td>\n",
    "\t<td>Store identifier</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Item_Description</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Text Features</td>\n",
    "\t<td>Item Description</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Category_Name</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Text Features</td>\n",
    "\t<td>Category Name</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Vendor_Name</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Text Features</td>\n",
    "\t<td>Vendor Name</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Store_Name</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Text Features</td>\n",
    "\t<td>Store Name</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Address</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Text Features</td>\n",
    "\t<td>Address</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>City</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Categorical Features</td>\n",
    "\t<td>City</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Zip_Code</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Categorical Features</td>\n",
    "\t<td>Zip-code</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Store_Location</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Categorical Features</td>\n",
    "\t<td>Store Location</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>County_Number</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Categorical Features</td>\n",
    "\t<td>County Number</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>County</td>\n",
    "\t<td>STRING</td>\n",
    "\t<td>Categorical Features</td>\n",
    "\t<td>County Name</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Weekly Sales Quantity</td>\n",
    "\t<td>INTEGER</td>\n",
    "\t<td>Time series data</td>\n",
    "\t<td>52 columns for weekly sales quantity from week 1 to week 52</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Weekly Sales Dollars</td>\n",
    "\t<td>INTEGER</td>\n",
    "\t<td>Time series data</td>\n",
    "\t<td>52 columns for weekly sales dollars from week 1 to week 52</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Inventory</td>\n",
    "\t<td>FLOAT</td>\n",
    "\t<td>Numeric Feature</td>\n",
    "\t<td>This inventory is stocked by the retailer looking at past sales and seasonality of the product to meet demand for future sales.</td>\n",
    "</tr>\n",
    "<tr>\n",
    "\t<td>Stockout</td>\n",
    "\t<td>INTEGER</td>\n",
    "\t<td>Label</td>\n",
    "\t<td>(1 - Stock-out, 0 - No stock-out) When the demand for four weeks future sales is not met by the inventory in stock we say we see a stock-out.\n",
    "    <br/>This is because an early warning sign would help the retailer re-stock inventory with a lead time for the stock to be replenished.</td>\n",
    "</tr>\n",
    "  </tbody>\n",
    "</table><br>\n",
    "To use AutoML Tables with BigQuery you do not need to download this dataset. However, if you would like to use AutoML Tables with GCS you may want to download this dataset and upload it into your GCP Project storage bucket. \n",
    "\n",
    "**Instructions to download dataset:**\n",
    "\n",
    "1. Sample Dataset: Download this dataset which contains sales data.\n",
    "\n",
    "\t* [Link to training data](https://console.cloud.google.com/bigquery?folder=&organizationId=&project=product-stockout&p=product-stockout&d=product_stockout&t=stockout&page=table):  \n",
    "\n",
    "\t\tDataset URI: <bq://product-stockout.product_stockout.stockout>\n",
    "\t* [Link to data for batch predictions](https://console.cloud.google.com/bigquery?folder=&organizationId=&project=product-stockout&p=product-stockout&d=product_stockout&t=batch_prediction_inputs&page=table):  \n",
    "\n",
    "\t\tDataset URI: <bq://product-stockout.product_stockout.batch_prediction_inputs>\n",
    "\n",
    "2. Upload this dataset to GCS or BigQuery (optional). \n",
    "\n",
    "\t* You could select either [GCS](https://cloud.google.com/storage/) or [BigQuery](https://cloud.google.com/bigquery/) as the location of your choice to store the data for this challenge. \n",
    "\n",
    "\t\t1. Storing data on GCS: [Creating storage buckets, Uploading data to storage buckets](https://cloud.google.com/storage/docs/creating-buckets)\n",
    "\t\t2. Storing data on BigQuery: [Create and load data to BigQuery](https://cloud.google.com/bigquery/docs/quickstarts/quickstart-web-ui) (optional)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "AD0-cRZ28MxI"
   },
   "source": [
    "### **Objective**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "TAqUXPbG7pV3"
   },
   "source": [
    "#### **Problem statement**\n",
    "A stockout, or out-of-stock (OOS) event is an event that causes inventory to be exhausted. While out-of-stocks can occur along the entire supply chain, the most visible kind are retail out-of-stocks in the fast-moving consumer goods industry (e.g., sweets, diapers, fruits). Stockouts are the opposite of overstocks, where too much inventory is retained.\n",
    "\n",
    "#### **Impact**\n",
    "According to a study by researchers Thomas Gruen and Daniel Corsten, the global average level of out-of-stocks within retail fast-moving consumer goods sector across developed economies was 8.3% in 2002. This means that shoppers would have a 42% chance of fulfilling a ten-item shopping list without encountering a stockout. Despite the initiatives designed to improve the collaboration of retailers and their suppliers, such as Efficient Consumer Response (ECR), and despite the increasing use of new technologies such as radio-frequency identification (RFID) and point-of-sale data analytics, this situation has improved little over the past decades.\n",
    "\n",
    "The biggest impacts being\n",
    "\n",
    "*   Customer dissatisfaction\n",
    "*   Loss of revenue\n",
    "\n",
    "\n",
    "\n",
    "#### **Machine Learning Solution**\n",
    "Using machine learning to solve for stock-outs can help with store operations and thus prevent out-of-stock proactively.\n",
    "\n",
    "There are three big challenges any retailer would face as they try and solve this problem with machine learning:\n",
    "\n",
    "1.   Data silos: Sales data, supply-chain data, inventory data, etc. may all be in silos. Such disjoint datasets could be a challenge to work with as a machine learning model tries to derive insights from all these data points.\n",
    "2.   Missing Features: Features such as vendor location, weather conditions, etc. could add a lot of value to a machine learning algorithm to learn from. But such features are not always available and when building machine learning solutions we think for collecting features as an iterative approach to improving the machine learning model.\n",
    "3.  Imbalanced dataset: Datasets for classification problems such as retail stock-out are traditionally very imbalanced with fewer cases for stock-out. Designing machine learning solutions by hand for such problems would be time consuming effort when your team should be focusing on collecting features.\n",
    "\n",
    "Hence, we recommend using AutoML Tables. With AutoML Tables you only need to work on acquiring all data and features, and AutoML Tables would do the rest. This is a one-click deploy to solving the problem of stock-out with machine learning."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "SLq3FfRa8E8X"
   },
   "source": [
    "### **Costs**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "DzxIfOrB71wl"
   },
   "source": [
    "This tutorial uses billable components of Google Cloud Platform (GCP):\n",
    "\n",
    "* Cloud AI Platform\n",
    "* Cloud Storage\n",
    "* BigQuery\n",
    "* AutoML Tables\n",
    "\n",
    "Learn about [Cloud AI Platform pricing](https://cloud.google.com/ml-engine/docs/pricing), [Cloud Storage pricing](https://cloud.google.com/storage/pricing), [BigQuery pricing](https://cloud.google.com/bigquery/pricing), [AutoML Tables pricing](https://cloud.google.com/automl-tables/pricing), and use the [Pricing Calculator](https://cloud.google.com/products/calculator/) to generate a cost estimate based on your projected usage."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ze4-nDLfK4pw"
   },
   "source": [
    "## **Set up your local development environment**\n",
    "\n",
    "**If you are using Colab or AI Platform Notebooks**, your environment already meets\n",
    "all the requirements to run this notebook. If you are using **AI Platform Notebook**, make sure the machine configuration type is **1 vCPU, 3.75 GB RAM** or above. You can skip this step."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "gCuSR8GkAgzl"
   },
   "source": [
    "**Otherwise**, make sure your environment meets this notebook's requirements.\n",
    "You need the following:\n",
    "\n",
    "* The Google Cloud SDK\n",
    "* Git\n",
    "* Python 3\n",
    "* virtualenv\n",
    "* Jupyter notebook running in a virtual environment with Python 3\n",
    "\n",
    "The Google Cloud guide to [Setting up a Python development\n",
    "environment](https://cloud.google.com/python/setup) and the [Jupyter\n",
    "installation guide](https://jupyter.org/install) provide detailed instructions\n",
    "for meeting these requirements. The following steps provide a condensed set of\n",
    "instructions:\n",
    "\n",
    "1. [Install and initialize the Cloud SDK.](https://cloud.google.com/sdk/docs/)\n",
    "\n",
    "2. [Install Python 3.](https://cloud.google.com/python/setup#installing_python)\n",
    "\n",
    "3. [Install\n",
    "   virtualenv](https://cloud.google.com/python/setup#installing_and_using_virtualenv)\n",
    "   and create a virtual environment that uses Python 3.\n",
    "\n",
    "4. Activate that environment and run `pip install jupyter` in a shell to install\n",
    "   Jupyter.\n",
    "\n",
    "5. Run `jupyter notebook` in a shell to launch Jupyter.\n",
    "\n",
    "6. Open this notebook in the Jupyter Notebook Dashboard."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "BF1j6f9HApxa"
   },
   "source": [
    "## **Set up your GCP project**\n",
    "\n",
    "**The following steps are required, regardless of your notebook environment.**\n",
    "\n",
    "1. [Select or create a GCP project.](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
    "\n",
    "2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
    "\n",
    "3. [Enable the AI Platform APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\n",
    "\n",
    "4. [Enable AutoML API.](https://console.cloud.google.com/apis/library/automl.googleapis.com?q=automl)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "i7EUnXsZhAGF"
   },
   "source": [
    "## **PIP Install Packages and dependencies**\n",
    "\n",
    "Install addional dependencies not installed in Notebook environment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "wyy5Lbnzg5fi"
   },
   "outputs": [],
   "source": [
    "! pip install --upgrade --quiet --user google-cloud-automl\n",
    "! pip install matplotlib"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kK5JATKPNf3I"
   },
   "source": [
    "**Note:** Try installing using `sudo`, if the above command throw any permission errors."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "f-YlNVLTYXXN"
   },
   "source": [
    "`Restart` the kernel to allow automl_v1beta1 to be imported for Jupyter Notebooks.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "C16j_LPrYbZa"
   },
   "outputs": [],
   "source": [
    "from IPython.core.display import HTML\n",
    "HTML(\"<script>Jupyter.notebook.kernel.restart()</script>\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "GWpby48cF6U7"
   },
   "source": [
    "## **Set up your GCP Project Id**\n",
    "\n",
    "Enter your `Project Id` in the cell below. Then run the  cell to make sure the\n",
    "Cloud SDK uses the right project for all the commands in this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "oM1iC_MfAts1"
   },
   "outputs": [],
   "source": [
    "PROJECT_ID = \"[your-project-id]\" #@param {type:\"string\"}\n",
    "COMPUTE_REGION = \"us-central1\" # Currently only supported region."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "dr--iN2kAylZ"
   },
   "source": [
    "## **Authenticate your GCP account**\n",
    "\n",
    "**If you are using AI Platform Notebooks**, your environment is already\n",
    "authenticated. Skip this step."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "3yyVCJHFSEKG"
   },
   "source": [
    "Otherwise, follow these steps:\n",
    "\n",
    "1. In the GCP Console, go to the [**Create service account key**\n",
    "   page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
    "\n",
    "2. From the **Service account** drop-down list, select **New service account**.\n",
    "\n",
    "3. In the **Service account name** field, enter a name.\n",
    "\n",
    "4. From the **Role** drop-down list, select\n",
    "   **AutoML > AutoML Admin**,\n",
    "   **Storage > Storage Object Admin** and **BigQuery > BigQuery Admin**.\n",
    "\n",
    "5. Click *Create*. A JSON file that contains your key downloads to your\n",
    "local environment."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Yt6PhVG0UdF1"
   },
   "source": [
    "**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "q5TeVHKDMOJF"
   },
   "outputs": [],
   "source": [
    "# Upload the downloaded JSON file that contains your key.\n",
    "import sys\n",
    "\n",
    "if 'google.colab' in sys.modules:    \n",
    "  from google.colab import files\n",
    "  keyfile_upload = files.upload()\n",
    "  keyfile = list(keyfile_upload.keys())[0]\n",
    "  %env GOOGLE_APPLICATION_CREDENTIALS $keyfile\n",
    "  ! gcloud auth activate-service-account --key-file $keyfile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "d1bnPeDVMR5Q"
   },
   "source": [
    "***If you are running the notebook locally***, enter the path to your service account key as the `GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "fsVNKXESYoeQ"
   },
   "outputs": [],
   "source": [
    "# If you are running this notebook locally, replace the string below with the\n",
    "# path to your service account key and run this cell to authenticate your GCP\n",
    "# account.\n",
    "\n",
    "%env GOOGLE_APPLICATION_CREDENTIALS /path/to/service/account\n",
    "! gcloud auth activate-service-account --key-file '/path/to/service/account'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "zgPO1eR3CYjk"
   },
   "source": [
    "## **Create a Cloud Storage bucket**\n",
    "\n",
    "**The following steps are required, regardless of your notebook environment.**\n",
    "\n",
    "When you submit a training job using the Cloud SDK, you upload a Python package\n",
    "containing your training code to a Cloud Storage bucket. AI Platform runs\n",
    "the code from this package. In this tutorial, AI Platform also saves the\n",
    "trained model that results from your job in the same bucket. You can then\n",
    "create an AI Platform model version based on this output in order to serve\n",
    "online predictions.\n",
    "\n",
    "Set the name of your Cloud Storage bucket below. It must be unique across all\n",
    "Cloud Storage buckets. \n",
    "\n",
    "You may also change the `REGION` variable, which is used for operations\n",
    "throughout the rest of this notebook. Make sure to [choose a region where Cloud\n",
    "AI Platform services are\n",
    "available](https://cloud.google.com/ml-engine/docs/tensorflow/regions). You may\n",
    "not use a Multi-Regional Storage bucket for training with AI Platform."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "both",
    "colab": {},
    "colab_type": "code",
    "id": "MzGDU7TWdts_"
   },
   "outputs": [],
   "source": [
    "BUCKET_NAME = \"[your-bucket-name]\" #@param {type:\"string\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "-EcIXiGsCePi"
   },
   "source": [
    "**Only if your bucket doesn't exist**: Run the following cell to create your Cloud Storage bucket. Make sure Storage > Storage Admin role is enabled"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "NIq7R4HZCfIc"
   },
   "outputs": [],
   "source": [
    "! gsutil mb -p $PROJECT_ID -l $COMPUTE_REGION gs://$BUCKET_NAME"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ucvCsknMCims"
   },
   "source": [
    "Finally, validate access to your Cloud Storage bucket by examining its contents:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "vhOb7YnwClBb"
   },
   "outputs": [],
   "source": [
    "! gsutil ls -al gs://$BUCKET_NAME"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "XoEqT2Y4DJmf"
   },
   "source": [
    "## **Import libraries and define constants**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Y9Uo3tifg1kx"
   },
   "source": [
    "Import relevant packages.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "pRUOFELefqf1"
   },
   "outputs": [],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "02J-91J6ZMUk"
   },
   "outputs": [],
   "source": [
    "# AutoML library.\n",
    "from google.cloud import automl_v1beta1 as automl\n",
    "import google.cloud.automl_v1beta1.proto.data_types_pb2 as data_types\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "WIoaocE_ITKY"
   },
   "source": [
    "Populate the following cell with the necessary constants and run it to initialize constants."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "1e9hznN_IUej"
   },
   "outputs": [],
   "source": [
    "#@title Constants { vertical-output: true }\n",
    "\n",
    "# A name for the AutoML tables Dataset to create.\n",
    "DATASET_DISPLAY_NAME = 'stockout_data' #@param {type: 'string'}\n",
    "# The BigQuery Dataset URI to import data from.\n",
    "BQ_INPUT_URI = 'bq://product-stockout.product_stockout.stockout' #@param {type: 'string'}\n",
    "# A name for the AutoML tables model to create.\n",
    "MODEL_DISPLAY_NAME = 'stockout_model' #@param {type: 'string'}\n",
    "\n",
    "assert all([\n",
    "    PROJECT_ID,\n",
    "    COMPUTE_REGION,\n",
    "    DATASET_DISPLAY_NAME,\n",
    "    BQ_INPUT_URI,\n",
    "    MODEL_DISPLAY_NAME,\n",
    "])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "MLtmkt7GbGlC"
   },
   "source": [
    "Initialize the client for AutoML and AutoML Tables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "fZiTNuQmcBoN"
   },
   "outputs": [],
   "source": [
    "# Initialize the clients.\n",
    "automl_client = automl.AutoMlClient()\n",
    "tables_client = automl.TablesClient(project=PROJECT_ID, region=COMPUTE_REGION)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "xdJykMXDozoP"
   },
   "source": [
    "## **Test the set up**\n",
    "\n",
    "To test whether your project set up and authentication steps were successful, run the following cell to list your datasets in this project.\n",
    "\n",
    "If no dataset has previously imported into AutoML Tables, you shall expect an empty return."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "_dKylOQTpF58"
   },
   "outputs": [],
   "source": [
    "# List the datasets.\n",
    "list_datasets = tables_client.list_datasets()\n",
    "datasets = { dataset.display_name: dataset.name for dataset in list_datasets }\n",
    "datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "dleTdOMaplSM"
   },
   "source": [
    "You can also print the list of your models by running the following cell.\n",
    "\n",
    "If no model has previously trained using AutoML Tables, you shall expect an empty return.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "tMXP6no1pn9p"
   },
   "outputs": [],
   "source": [
    "# List the models.\n",
    "list_models = tables_client.list_models()\n",
    "models = { model.display_name: model.name for model in list_models }\n",
    "models"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "RzzzdXANp858"
   },
   "source": [
    "## **Import training data**\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "5i8PBNWJ3rAv"
   },
   "source": [
    "#### **Create dataset**\n",
    "\n",
    "Select a dataset display name and pass your table source information to create a new dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "OXddfTPoqO1Z"
   },
   "outputs": [],
   "source": [
    "# Create dataset.\n",
    "dataset = tables_client.create_dataset(DATASET_DISPLAY_NAME)\n",
    "dataset_name = dataset.name\n",
    "dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "InYuWIf5qQe7"
   },
   "source": [
    "#### **Import data**\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "aNJvoyOAmAOf"
   },
   "source": [
    "You can import your data to AutoML Tables from GCS or BigQuery. For this solution, you will import data from a BigQuery Table. The URI for your table is in the format of `bq://PROJECT_ID.DATASET_ID.TABLE_ID`.\n",
    "\n",
    "The BigQuery Table used for demonstration purpose can be accessed as `bq://product-stockout.product_stockout.stockout`.\n",
    "\n",
    "See the table schema and dataset description from the README."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Mzjb3xgLsPb7"
   },
   "outputs": [],
   "source": [
    "# Import data.\n",
    "import_data_response = tables_client.import_data(\n",
    "    dataset=dataset,\n",
    "    bigquery_input_uri=BQ_INPUT_URI,\n",
    ")\n",
    "print('Dataset import operation: {}'.format(import_data_response.operation))\n",
    "\n",
    "# Synchronous check of operation status. Wait until import is done.\n",
    "print('Dataset import response: {}'.format(import_data_response.result()))\n",
    "\n",
    "# Verify the status by checking the example_count field.\n",
    "dataset = tables_client.get_dataset(dataset_name=dataset_name)\n",
    "dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "gxVzEhiBqfWr"
   },
   "source": [
    "Importing this stockout datasets takes about 10 minutes.\n",
    "\n",
    "If you re-visit this Notebook, uncomment the following cell and run the command to retrieve your dataset. Replace `YOUR_DATASET_NAME` with its actual value obtained in the preceding cells.\n",
    "\n",
    "`YOUR_DATASET_NAME` is a string in the format of `'projects/<project_id>/locations/<location>/datasets/<dataset_id>'`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "fpP1xWscqhJ8"
   },
   "outputs": [],
   "source": [
    "# dataset_name = '<YOUR_DATASET_NAME>' #@param {type: 'string'}\n",
    "# dataset = tables_client.get_dataset(dataset_name=dataset_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Neewv2bXqkFf"
   },
   "source": [
    "## **Review the specs**\n",
    "Run the following command to see table specs such as row count."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "jn5-g-RwquOd"
   },
   "outputs": [],
   "source": [
    "# List table specs.\n",
    "list_table_specs_response = tables_client.list_table_specs(dataset=dataset)\n",
    "table_specs = [s for s in list_table_specs_response]\n",
    "\n",
    "# List column specs.\n",
    "list_column_specs_response = tables_client.list_column_specs(dataset=dataset)\n",
    "column_specs = {s.display_name: s for s in list_column_specs_response}\n",
    "\n",
    "# Print Features and data_type.\n",
    "features = [(key, data_types.TypeCode.Name(value.data_type.type_code))\n",
    "            for key, value in column_specs.items()]\n",
    "print('Feature list:\\n')\n",
    "for feature in features:\n",
    "    print(feature[0],':', feature[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "63QFqQfxqyCR"
   },
   "outputs": [],
   "source": [
    "# Table schema pie chart.\n",
    "type_counts = {}\n",
    "for column_spec in column_specs.values():\n",
    "  type_name = data_types.TypeCode.Name(column_spec.data_type.type_code)\n",
    "  type_counts[type_name] = type_counts.get(type_name, 0) + 1\n",
    "    \n",
    "plt.pie(x=type_counts.values(), labels=type_counts.keys(), autopct='%1.1f%%')\n",
    "plt.axis('equal')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "opNreHuMqzJJ"
   },
   "source": [
    "In the pie chart above, you see this dataset contains three variable types: `FLOAT64` (treated as `Numeric`), `CATEGORY` (treated as `Categorical`) and `STRING` (treated as `Text`). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "avNsksNFrEAa"
   },
   "source": [
    "## **Update dataset: assign a label column and enable nullable columns**\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Dk2jFo274O-z"
   },
   "source": [
    "#### **Get column specs**\n",
    "\n",
    "AutoML Tables automatically detects your data column type.\n",
    "\n",
    "There are a total of 120 columns in this stockout dataset.\n",
    "\n",
    "Run the following command to check the column data type that automaticallyed detected. If columns contains only numerical values, but they represent categories, change that column data type to caregorical by updating your schema.\n",
    "\n",
    "In addition, AutoML Tables detects `Stockout` to be categorical that chooses to run a classification model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "jvF9_3ierVdu"
   },
   "outputs": [],
   "source": [
    "# Print column data types.\n",
    "for column in column_specs:\n",
    "    print(column, '-', column_specs[column].data_type)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "fGamAlLgrXnL"
   },
   "source": [
    "#### **Update columns: make categorical**\n",
    "\n",
    "From the column data type, you noticed `Item_Number`, `Category`, `Vendor_Number`, `Store_Number`, `Zip_Code` and `County_Number` have been autodetected as `FLOAT64` (Numerical) instead of `CATEGORY` (Categorical). \n",
    "\n",
    "In this solution, the columns `Item_Number`, `Category`, `Vendor_Number` and `Store_Number` are not nullable, but `Zip_Code` and `County_Number` can take null values.\n",
    "\n",
    "To change the data type, you can update the schema by updating the column spec."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "5PhtaixArclw"
   },
   "outputs": [],
   "source": [
    "type_code='CATEGORY' #@param {type:'string'}\n",
    "\n",
    "# Update dataset.\n",
    "categorical_column_names = ['Item_Number', 'Category', 'Vendor_Number', \n",
    "                            'Store_Number', 'Zip_Code', 'County_Number']\n",
    "\n",
    "is_nullable = [False, False, False, False, True, True]                      \n",
    "\n",
    "for i in range(len(categorical_column_names)):\n",
    "    column_name = categorical_column_names[i]\n",
    "    nullable = is_nullable[i]\n",
    "    tables_client.update_column_spec(\n",
    "        dataset=dataset,\n",
    "        column_spec_display_name=column_name,\n",
    "        type_code=type_code,\n",
    "        nullable=nullable,\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ypBV6myxrjTw"
   },
   "source": [
    "#### **Update dataset: Assign a label**\n",
    "Select the target column and update the dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "x1X4jv3-rnO4"
   },
   "outputs": [],
   "source": [
    "#@title Update dataset { vertical-output: true }\n",
    "\n",
    "target_column_name = 'Stockout' #@param {type: 'string'}\n",
    "update_dataset_response = tables_client.set_target_column(\n",
    "    dataset=dataset,\n",
    "    column_spec_display_name=target_column_name,\n",
    ")\n",
    "update_dataset_response"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "qlCneadcrvoi"
   },
   "source": [
    "## **Creating a model**\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "oCJkY5bX4clh"
   },
   "source": [
    "#### **Train a model**\n",
    "\n",
    "Training the model may take one hour or more. To obtain the results with less training time or budget, you can set [`train_budget_milli_node_hours`](https://cloud.google.com/automl-tables/docs/reference/rest/v1beta1/projects.locations.models), which is the train budget of creating this model, expressed in milli node hours i.e. 1,000 value in this field means 1 node hour.\n",
    "\n",
    "For demonstration purpose, the following command sets the budget as 1 node hour `('train_budget_milli_node_hours': 1000)`. You can increase that number up to a maximum of 72 hours `('train_budget_milli_node_hours': 72000)` for the best model performance.\n",
    "\n",
    "Even with a budget of 1 node hour (the minimum possible budget), training a model can take more than the specified node hours\n",
    "\n",
    "You can also select the objective to optimize your model training by setting `optimization_objective`. This solution optimizes the model by maximizing the Area Under the Precision-Recall (PR) Curve."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "fq5Lvt66r0gK"
   },
   "outputs": [],
   "source": [
    "# The number of hours to train the model.\n",
    "model_train_hours = 1 #@param {type:'integer'}\n",
    "# Set optimization objective to train a model.\n",
    "model_optimization_objective = 'MAXIMIZE_AU_PRC' #@param {type:'string'}\n",
    "\n",
    "create_model_response = tables_client.create_model(\n",
    "    MODEL_DISPLAY_NAME,\n",
    "    dataset=dataset,\n",
    "    train_budget_milli_node_hours=model_train_hours*1000,\n",
    "    optimization_objective=model_optimization_objective,\n",
    ")\n",
    "operation_id = create_model_response.operation.name\n",
    "\n",
    "print('Create model operation: {}'.format(create_model_response.operation))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "7YJy1jh2VXRl"
   },
   "outputs": [],
   "source": [
    "# Wait until model training is done.\n",
    "model = create_model_response.result()\n",
    "model_name = model.name\n",
    "model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Y0U3o4hmr3co"
   },
   "source": [
    "If your Colab times out, use `tables_client.list_models()` to check whether your model has been created.\n",
    "\n",
    "Then uncomment the following cell and run the command to retrieve your model. Replace `YOUR_MODEL_NAME` with its actual value obtained in the preceding cell.\n",
    "\n",
    "`YOUR_MODEL_NAME` is a string in the format of `'projects/<project_id>/locations/<location>/models/<model_id>'`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "2bVZsL6Er5XN"
   },
   "outputs": [],
   "source": [
    "#model_name = '<YOUR_MODEL_NAME>' #@param {type: 'string'}\n",
    "# model = tables_client.get_model(model_name=model_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "yCrBEllhr--f"
   },
   "source": [
    "## **Batch prediction**\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Z-RklZCA4j_3"
   },
   "source": [
    "#### **Initialize prediction**\n",
    "\n",
    "Your data source for batch prediction can be GCS or BigQuery. For this solution, you will use a BigQuery Table as the input source. The URI for your table is in the format of `bq://PROJECT_ID.DATASET_ID.TABLE_ID`.\n",
    "\n",
    "To write out the predictions, you need to specify a GCS bucket `gs://BUCKET_NAME`.\n",
    "\n",
    "The AutoML Tables logs the errors in the `errors.csv` file.\n",
    "\n",
    "**NOTE:** The batch prediction output file(s) will be updated to the GCS bucket that you set in the preceding cells."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "tgS55lD8sJUi"
   },
   "outputs": [],
   "source": [
    "#@title Start batch prediction { vertical-output: true, output-height: 200 }\n",
    "batch_predict_bq_input_uri = 'bq://product-stockout.product_stockout.batch_prediction_inputs' #@param {type:'string'}\n",
    "batch_predict_gcs_output_uri_prefix = 'gs://{}'.format(BUCKET_NAME)  #@param {type:'string'}\n",
    "\n",
    "batch_predict_response = tables_client.batch_predict(\n",
    "    model_name=model_name, \n",
    "    bigquery_input_uri=batch_predict_bq_input_uri,\n",
    "    gcs_output_uri_prefix=batch_predict_gcs_output_uri_prefix,\n",
    ")\n",
    "print('Batch prediction operation: {}'.format(batch_predict_response.operation))\n",
    "\n",
    "# Wait until batch prediction is done.\n",
    "batch_predict_result = batch_predict_response.result()\n",
    "batch_predict_response.metadata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "JCa218LosND5"
   },
   "outputs": [],
   "source": [
    "# Check prediction results.\n",
    "gcs_output_directory = batch_predict_response.metadata.batch_predict_details\\\n",
    "                       .output_info.gcs_output_directory\n",
    "result_file = gcs_output_directory + 'tables_1.csv'\n",
    "print('Batch prediction results are stored as: {}'.format(result_file))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "TpV-iwP9qw9c"
   },
   "source": [
    "## **Cleaning up**\n",
    "\n",
    "To clean up all GCP resources used in this project, you can [delete the GCP\n",
    "project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "sx_vKniMq9ZX"
   },
   "outputs": [],
   "source": [
    "# Delete model resource.\n",
    "tables_client.delete_model(model_name=model_name)\n",
    "\n",
    "# Delete dataset resource.\n",
    "tables_client.delete_dataset(dataset_name=dataset_name)\n",
    "\n",
    "# Delete Cloud Storage objects that were created.\n",
    "! gsutil -m rm -r gs://$BUCKET_NAME\n",
    "\n",
    "# If training model is still running, cancel it.\n",
    "automl_client.transport._operations_client.cancel_operation(operation_id)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "retail_product_stockout_prediction.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
